#include <iostream>
// #include <string>
#include <memory>
#include <sys/epoll.h>

#include "Socket.hpp"

using namespace SockModule;
using namespace LogModule;

#define MAX 1024

const int default_fd = -1;

class EpollSvr
{
    static const int _nr_ev = 64;
public:
    EpollSvr(uint16_t port)
        : _port(port)
        , _listen_sock(std::make_unique<TcpSocket>())
        , _epfd(default_fd)
        , _isrunning(false)
    {
    }

    ~EpollSvr() {}

    void Init()
    {
        _listen_sock->BuildTcpSocket(_port);
        _epfd = epoll_create(10086);
        if(_epfd < 0){
            LOG(LogLevel::ERROR) << "epoll_create error";
            exit(EPOLL_CREATE_ERR);
        }
        LOG(LogLevel::DEBUG) << "epoll_create success: " << _epfd;
        struct epoll_event ev;
        ev.events = EPOLLIN;
        ev.data.fd = _listen_sock->Fd();
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _listen_sock->Fd(), &ev);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_ctl error";
            exit(EPOLL_CTL_ERR);
        }
    }
    void Loop()
    {
        _isrunning = true;
        
        // int milliSec = 0; // 非阻塞
        int milliSec = -1; // 一直阻塞
        // int milliSec = 1000; // 一秒内阻塞 超过一秒非阻塞
        while (_isrunning)
        {
            int n = epoll_wait(_epfd, _rc_ev, _nr_ev, milliSec);
            switch (n)
            {
            case 0:
                std::cout << "timeout ..." << std::endl;
                break;
            case -1:
                perror("Epoll: ");
                break;
            default:
                std::cout << "IO affair ready." << std::endl;
                Dispatcher(n);
                break;
            }
        }

        _isrunning = false;
    }
    void Accepter()
    {
        InetAddr client;
        int newfd = _listen_sock->Accepter(&client);
        if (newfd < 0)
            return;


        std::cout << "获得了一个新的链接: " << newfd << " client info: " << client.Addr() << std::endl;
        epoll_event ev;
        ev.data.fd = newfd;
        ev.events = EPOLLIN;
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, newfd, &ev);
        
        if(n < 0){
            LOG(LogLevel::ERROR) << "epoll_ctl Error";
            close(newfd);
        }
        LOG(LogLevel::DEBUG) << "epoll_ctl success: " << newfd;
    }
    void Recever(int fd)
    {
        char buffer[1024];
        ssize_t n = recv(fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " << buffer << std::endl;
            // 回显
            std::string msg = "echo# ";
            msg += buffer;
            send(fd, msg.c_str(), msg.size(), 0); // bug
        }
        else if (n == 0)
        {
            // 远端关闭
            LOG(LogLevel::DEBUG) << "客户端退出, sockfd: " << fd;
            // 复原
            int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            if(m < 0){
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                return;
            }
            close(fd);
            // 由于 之前的 select poll 代码的辅助数组是我们自己管理,所以可以先close 再 修改数组,但是并不建议,因为如果是内核管理
            // 辅助数组的话,就需要先修改辅助数组再 close(fd)
        }
        else
        {
            LOG(LogLevel::DEBUG) << "客户端读取出错, sockfd: " <<  fd;
            int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            if(m < 0){
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                return;
            }
            close(fd);
        }
    }
    void Dispatcher(int nr_to_dispatch)
    {
        for (int i = 0; i < nr_to_dispatch; ++i)
        {
            // 合法的fd
            if (_rc_ev[i].data.fd == _listen_sock->Fd())
            {
                // listen_sockfd
                if (_rc_ev[i].events & EPOLLIN)
                {
                    Accepter();
                }
            }
            else
            {
                if (_rc_ev[i].events & EPOLLIN)
                {
                    Recever(_rc_ev[i].data.fd);
                }
                // else if(_fds[i]->revents & POLLOUT){
                //     //write
                // }
            }
        }
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_sock;
    bool _isrunning;
    int _epfd;
    struct epoll_event _rc_ev[_nr_ev];
};
